package mysql

import (
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	"github.com/spf13/viper"
	_ "net/http"
	"time"
	_ "time"
)

var db *gorm.DB

// InitDB mysql数据库连接
func InitDB() error {

	driverName := viper.GetString("mysql.driverName")
	host := viper.GetString("mysql.host")
	port := viper.GetString("mysql.port")
	database := viper.GetString("mysql.database")
	username := viper.GetString("mysql.username")
	password := viper.GetString("mysql.password")
	charset := viper.GetString("mysql.charset")

	args := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=true",
		username,
		password,
		host,
		port,
		database,
		charset,
	)

	sqlDb, err := gorm.Open(driverName, args)
	db = sqlDb

	db.SingularTable(true) //禁止gorm给表名自动加s后缀

	if err != nil {
		panic("failed to connect databases,err:" + err.Error())
	}

	db.DB().SetMaxIdleConns(viper.GetInt("maxConn"))                           //设置最大连接数
	db.DB().SetMaxOpenConns(viper.GetInt("maxOpen"))                           //最大空闲连接数
	db.DB().SetConnMaxLifetime(time.Duration(viper.GetInt("connMaxLifetime"))) //设置连接最大生存时间

	return db.DB().Ping()
}

func Db() *gorm.DB {
	return db
}

func Close() {
	err := db.Close()
	if err != nil {
		panic(err)
	}
}
